<template>
	<div class="bg">
		<div class="login">
			<el-card class="form-card">
				<div slot="header" class="clearfix">
					<span>登录</span>
				</div>
				<el-form label-position="right" ref='form' :model="form" :rules="rules" label-width="80px">
					<el-form-item label="账号" prop='username'>
						<el-input type="text" v-model="form.username" placeholder="请输入用户名!"></el-input>
					</el-form-item>
					<el-form-item label="密码" prop='password'>
						<el-input type="password" v-model="form.password" placeholder="请输入密码!"></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click='handleLogin'>登录</el-button>
					</el-form-item>
				</el-form>
				<div class="action-box">
					<el-link href="#/register" target="info">注册账号</el-link>
					<el-link href="#/" target="info">忘记密码？</el-link>
				</div>
			</el-card>
		</div>
	</div>
</template>

<script>
	import { Admin } from '@/api/';

	export default {
		data() {
			return {
				form: {
					username: '',
					password: '',
				},
				rules: {
					username: [
						{ required: true, message: '请输入账户名称', trigger: 'blur' },
						{ min: 3, max: 20, message: '长度在 3 到 5 个字符', trigger: 'blur' }
					],
					password: [
						{ required: true, message: '请输入密码', trigger: 'blur' },
						{ pattern: /^\d{3,15}$/, message: '长度在 3 到 20位数字', trigger: 'blur' }
					]
				}
			}
		},
		methods: {

			handleLogin() {
				this.$refs.form.validate( async (valid) => {
					if (valid) {
						//发送ajax
						let { status, msg, data } = await Admin.login({ ...this.form });
						if (status) {
							//缓存数据
							sessionStorage.id = data.id;
							sessionStorage.role = data.role;
							sessionStorage.token = data.token;
							//提示成功
							this.$message.success(msg);
							//跳转页面
							let { redirect } = this.$route.query;
							if (redirect) {
								this.$router.replace(redirect);
							} else {
								this.$router.replace('/goods/list');
							}
						} else {
							//提示失败
							this.$message.error(msg);
						}
					}
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.bg {
		width: 100vw;
		height: 100vh;
		background: url(~@/assets/img/login/bg.jpg) no-repeat top center;
		background-size: cover;

		.form-card {
			width: 365px;
			position: absolute;
			top: 50%;
			right: 100px;
			transform: translateY(-50%-15px);

			.action-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}
	}
</style>
